package guava;

import com.google.common.annotations.Beta;
import com.google.common.collect.Maps;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

public class PropsKit {

    public static Map<String,String> getProp(String propFileName){
        URL url = PropsKit.class.getClassLoader().getResource(propFileName);
        Map<String,String> props = null;
        try {
            props = Resources.readLines(url, Charset.forName("utf-8"),
                    new PropLineProcessor());
        } catch (IOException e) {
            System.err.println(e); // TODO: 改为slf4j
            throw new RuntimeException(e);
        }
        return props;
    }

    @Beta
    private static class PropLineProcessor implements LineProcessor<Map<String,String>> {
        final Map<String,String> map = Maps.newHashMap();
        @Override
        public boolean processLine(String line) throws IOException {
            if(line.startsWith("#")) return true;
            if(line.contains("=")){
                String[] arr = line.split("=");
                map.put(arr[0].trim(), arr[1].trim());
            }
            return true;
        }

        @Override
        public Map<String,String> getResult() {
            return map;
        }
    }
}
